<template>
  <div>
    <el-container>
      <el-aside width="300px">
        <el-card :style="`height:${height}px`" class="box-card">
          <div slot="header" class="clearfix">
            <span>组织机构</span>
          </div>
          <leftTree @nodeClick="getNode" treeType="1"></leftTree>
        </el-card>
      </el-aside>
      <el-main>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>角色信息表</span>
          </div>
          <el-form size="mini" :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="角色名称">
              <el-input clearable v-model="formInline.user" placeholder="角色名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
              <el-button type="primary" @click="dialogVisible = true">新增</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="tableData" :height="heightTab" border style="width: 100%">
            <el-table-column type="selection" width="40"></el-table-column>
            <el-table-column prop="rolename" label="角色名称"></el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
            <el-table-column fixed="right" label="操作" width="220">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="authorizeUser(scope.row)">授权用户</el-button>
                <el-button type="text" size="small" @click="authorizeUserClear(scope.row)">取消授权用户</el-button>
                <el-button type="text" size="small" @click="delPerson(scope.row.account)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-main>
    </el-container>
    <el-dialog title="新增角色" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="角色名称" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="所属部门" prop="org">
          <select-tree
            @treeNode="treeNode"
            v-model="form.org"
            :options="options"
            :props="defaultProps"
          />
        </el-form-item>
        <el-form-item label="登陆账户" prop="account">
          <el-input v-model="form.account"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="form.pwd"></el-input>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input type="password" v-model="form.pwds"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="form.lxdh"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save('form')">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="授权用户" :visible.sync="authorizeVisible" width="40%">
      <el-form size="mini" :inline="true" :model="authorizeForm" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input clearable v-model="authorizeForm.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="authorizeSearch">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table ref="userTable" :data="tableDataUser" height="250" border style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="deptname" label="部门名称"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="authorizeVisible = false">取 消</el-button>
        <el-button type="primary" @click="addusertorole">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="取消授权用户" :visible.sync="authorizeVisibleClear" width="40%">
      <el-form size="mini" :inline="true" :model="authorizeFormClear" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input clearable v-model="authorizeFormClear.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="authorizeSearchClear">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table ref="userTableClear" :data="tableDataUserClear" height="250" border style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <!-- <el-table-column prop="deptname" label="部门名称"></el-table-column> -->
        <el-table-column prop="username" label="姓名"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="authorizeVisibleClear = false">取 消</el-button>
        <el-button type="primary" @click="addusertoroleClear ">确 定</el-button>
      </span>
    </el-dialog>
  </div>  
</template>
<script>
const leftTree = () => import("@/components/leftTree");
const SelectTree = () => import("@/components/SelectTree");
export default {
  data() {
    return {
      height: window.innerHeight - 140,
      heightTab: window.innerHeight - 310,
      formInline: {
        user: "",
        region: "",
      },
      tableData: [],
      currentPage: 1,
      dialogVisible: false,
      authorizeVisible: false,
      authorizeVisibleClear: false,
      form: {
        account: "",
        pwd: "",
        pwds: "",
        date2: "",
        lxdh: "",
        org: "",
        sex: "",
      },
      defaultProps: {
        parent: "parentId", // 父级唯一标识
        value: "id", // 唯一标识
        label: "name", // 标签显示
        children: "children", // 子级
      },
      // 数据列表
      options: [],
      tableDataAll: [],
      leftTreeNode: "",
      rules: {
        username: [
          { required: true, message: "请输入人员名称", trigger: "blur" },
        ],
        account: [
          { required: true, message: "请输入登陆账号", trigger: "blur" },
        ],
        org: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
      },
      tableDataUser: [],
      tableDataUserAll: [],
      authorizeForm: {
        name: "",
      },
      authorizeFormClear: {
        name: "",
      },
      authorizeUserId: "",
      tableDataUserClear: [],
      tableDataUserClearAll: [],
    };
  },
  components: {
    leftTree: leftTree,
    "select-tree": SelectTree,
  },
  methods: {
    treeNode(data) {
      this.form["deptid"] = data.id;
      this.form["deptname"] = data.name;
    },
    getPerson() {
      this.$ajax.get(`/admin/getrolelist`).then((res) => {
        this.tableData = res.data;
        this.tableDataAll = res.data;
      });
    },
    hisSys() {
      this.$ajax.post("/admin/syncHisUser", this.form).then((res) => {
        if (res.code == 0) {
          this.$message({
            message: "添加成功",
            type: "success",
          });
          this.getPerson();
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
    search() {
      if (this.formInline.user != "") {
        this.tableData = [];
        this.tableDataAll.forEach((item) => {
          if (item.username.indexOf(this.formInline.user) != -1) {
            this.tableData.push(item);
          }
        });
      } else {
        this.tableData = this.tableDataAll;
      }
    },
    delPerson(data) {
      this.$confirm("此操作将永久删除该人员, 是否继续?", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          this.$ajax
            .post("/admin/deleteuser", { account: data })
            .then((res) => {
              if (res.code == 0) {
                this.$message({
                  message: "删除成功",
                  type: "success",
                });
                this.getPerson();
              } else {
                this.$message({
                  message: res.msg,
                  type: "error",
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form["pwd"] != this.form["pwds"]) {
            this.$message.error("2次密码一致");
            return;
          }
          this.$ajax.post("/admin/adduser", this.form).then((res) => {
            if (res.code == 0) {
              this.$message({
                message: "新增成功",
                type: "success",
              });
              this.dialogVisible = false;
              this.getPerson();
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    getNode(data) {
      this.leftTreeNode = data.id;
      this.getPerson();
    },
    getOrgList() {
      this.$ajax.get("/admin/getOrg").then((res) => {
        this.options = res.data;
      });
    },
    getuserbydeptid() {
      return new Promise((resolve, reject) => {
        this.$ajax
          .get("/admin/getuserbydeptid")
          .then((res) => {
            resolve(res.data);
          })
          .catch((err) => {
            reject();
          });
      });
    },
    getuserlistbyrole(data) {
      return new Promise((resolve, reject) => {
        this.$ajax
          .get(`/admin/getuserlistbyrole?roleid=${data}`)
          .then((res) => {
            this.tableDataUserClear = res.data;
            this.tableDataUserClearAll = res.data;
            resolve(res.data);
          })
          .catch((err) => {
            reject();
          });
      });
    },
    authorizeUser(row) {
      this.authorizeUserId = row.roleid;
      this.authorizeVisible = true;
      Promise.all([this.getuserbydeptid(), this.getuserlistbyrole(row.roleid)])
        .then((res) => {
          this.tableDataUser = res[0];
          this.tableDataUserAll = res[0];
          this.$nextTick(() => {
            this.tableDataUser.forEach((el) => {
              res[1].forEach((item) => {
                if (el.id == item.id) {
                  this.$refs.userTable.toggleRowSelection(el, true);
                }
              });
            });
          });
        })
        .catch((err) => {
          // 抛出错误信息
        });
    },
    authorizeSearch() {
      if (this.authorizeForm.name != "") {
        this.tableDataUser = [];
        this.tableDataUserAll.forEach((item) => {
          if (item.username.indexOf(this.authorizeForm.name) != -1) {
            this.tableDataUser.push(item);
          }
        });
      } else {
        this.tableDataUser = this.tableDataUserAll;
      }
    },
    authorizeSearchClear() {
      if (this.authorizeFormClear.name != "") {
        this.tableDataUserClear = [];
        this.tableDataUserClearAll.forEach((item) => {
          if (item.username.indexOf(this.authorizeFormClear.name) != -1) {
            this.tableDataUserClear.push(item);
          }
        });
      } else {
        this.tableDataUserClear = this.tableDataUserClearAll;
      }
    },
    addusertorole() {
      let roleid;
      let selUsertable = this.$refs.userTable.selection;
      selUsertable.forEach((el) => {
        if (roleid) {
          roleid = `${el.id},${roleid}`;
        } else {
          roleid = `${el.id}`;
        }
      });
      let data = {
        roleid: this.authorizeUserId,
        userid: roleid,
      };
      this.$ajax.post("/admin/addusertorole", data).then((res) => {
        if (res.code == 0) {
          this.$message({
            message: "授权成功",
            type: "success",
          });
          this.authorizeVisible = false;
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
    authorizeUserClear(row) {
      this.authorizeVisibleClear = true;
      this.getuserlistbyrole(row.roleid);
    },
    addusertoroleClear() {
      let roleid;
      let selUsertable = this.$refs.userTableClear.selection;
      selUsertable.forEach((el) => {
        if (roleid) {
          roleid = `${el.id},${roleid}`;
        } else {
          roleid = `${el.id}`;
        }
      });
      let data = {
        roleid: this.authorizeUserId,
        userid: roleid,
      };
      this.$ajax.post("/admin/deleteuserfromrole", data).then((res) => {
        if (res.code == 0) {
          this.$message({
            message: "取消授权成功",
            type: "success",
          });
          this.authorizeVisibleClear = false;
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
  },
  mounted() {
    this.getPerson();
    this.getOrgList();
  },
};
</script>
<style lang="less" scoped>
.block {
  padding: 10px 0;
}
/deep/ .el-card__body {
  padding-bottom: 0;
}
</style>